import {
	BitSet,
	BitClr,
	Set2Byte,
	DataGet,
	ab2hex,
	hexCharCodeToStr,
	arrayToBuffer,
	Parse,
	paraconfigdata,
	Set3Byte,
	bitToStr,
	Set1Byte,
	feedback,
	Set4Byte,
	Get2Byte,
	Get4Byte,
	Get3Byte,
	getByBite,
	uploadEquipCommlog,
} from "@/utils/index.js";
import {
	masterMessage2,
	binMessage2,
	unitMessage2,
	resultMessage,
} from "@/pagesA/bluetooth/param/message.js";
import {
	serviceId,
	characteristicId3,
} from "@/utils/service.js";

import {
	READ_AND_WRITE_STATUS,
} from "@/common/config.js";
import {
	AESEncrypt
} from "@/utils/AesEncrypt.js";
export default {
	data() {
		return {
			startTime: null, //开始时间戳
		}
	},
	methods: {
		isRead() {
			let that = this;
			uni.showModal({
				title: '提示',
				content: '确定要查询吗？',
				success(res) {
					if (res.confirm) {
						that.doRead();
					}
				}
			})
		},
		// 读取设备信息
		async doRead(addr) {
			let that = this;
			that.$Toast.loading(`读取中...`);
			this.startTime = new Date().getTime();

			let datas = DataGet(this.command, 1, addr ? addr : 0, 0, 0, null);
			let buffer = arrayToBuffer(datas);
			let requestHex = ab2hex(buffer);

			let {
				deviceId,
			} = this.deviceInfo;
			uni.writeBLECharacteristicValue({
				deviceId,
				serviceId,
				characteristicId: characteristicId3,
				// 这里的value是ArrayBuffer类型
				value: buffer,
				success(res) {
					setTimeout(() => {
						that.doCharData(addr);
					}, 300)
					uploadEquipCommlog(requestHex, '', READ_AND_WRITE_STATUS[1], 1, that.startTime,
						that.deviceInfo, that.dgMessage);
				},
				fail(err) {
					console.log(err)
					that.$Toast.none(`${that.dgMessage}读取失败!`);

					uploadEquipCommlog(requestHex, '', READ_AND_WRITE_STATUS[1], 0, that.startTime,
						that.deviceInfo, that.dgMessage);
				}
			})
		},
		// 读取数据
		doCharData(addr) {
			let {
				deviceId,
			} = this.deviceInfo;
			let that = this;
			this.startTime = new Date().getTime();

			// 读取低功耗蓝牙设备的特征值的二进制数据值
			uni.readBLECharacteristicValue({
				deviceId,
				serviceId,
				characteristicId: characteristicId3,
				success(res) {
					uni.onBLECharacteristicValueChange(function(res) {
						uni.hideLoading();
						// 解析数据
						// let value = res.value ? ab2hex(res.value) : '';
						const uint8Array = new Uint8Array(res.value);
						const newArray = Array.from(uint8Array);
						let databuff = Parse(newArray);

						uploadEquipCommlog('', ab2hex(res.value), READ_AND_WRITE_STATUS[0], 1, that
							.startTime,
							that.deviceInfo, that.dgMessage);

						switch (databuff.dataUnit) {
							//数据单元 0：主控单元;1：检测单元;2：仓控单元;3：柜控电源单元;4：整流电源单元;5：电池单元;6：消防单元;7：充电电源
							case 0:
								if (databuff.databuff && databuff.databuff.length == 5) {
									for (let i = 0; i < databuff.databuff.length; i++) {
										that.masterInfo[`param${i+1}`] = databuff.databuff[i];
									}
								}
								break;
							case 1:
								// 检测单元参数查询
								if (databuff.databuff && databuff.databuff.length == 12) {
									// 输出过压阈值
									that.unitInfo.param1 = Get2Byte(databuff.databuff.slice(0, 2));
									// 输出欠压阈值
									that.unitInfo.param2 = databuff.databuff[2];
									// 输出过温阈值
									that.unitInfo.param3 = databuff.databuff[3];
									that.unitInfo.param4 = Get2Byte(databuff.databuff.slice(4, 6));

									for (let i = 5; i < databuff.databuff.length - 1; i++) {
										that.unitInfo[`param${i}`] = databuff.databuff[i + 1];
									}
								}
								break;
							case 2:
								if (databuff.databuff && databuff.databuff.length == 17) {
									that.binDetail.param1 = Get2Byte(databuff.databuff.slice(0, 2));

									for (let i = 1; i < 3; i++) {
										that.binDetail[`param${i+1}`] = databuff.databuff[i + 1];
									}
									let param4 = databuff.databuff[4];
									that.binDetail.param4 = (param4 / 10)
										.toFixed(1);

									that.binDetail.param5 = Get2Byte(databuff.databuff.slice(5, 7));

									for (let i = 6; i < 9; i++) {
										that.binDetail[`param${i}`] = databuff.databuff[i + 1];
									}

									for (let i = 9; i < 12; i++) {
										that.binDetail[`param${i}`] = Get2Byte(databuff.databuff.slice(
											i + 1, i + 3));
									}
									that.binDetail.param12 = databuff.databuff[16];
								}
								break;
						}
					})

				},
				fail(fal) {
					that.$Toast.none(`${that.dgMessage}读取失败!`);

					uploadEquipCommlog('', fal.errCode, READ_AND_WRITE_STATUS[0], 0, that.startTime,
						that.deviceInfo, that.dgMessage);
				}
			})
		},
		// 仓状态详情
		binPopup(index) {
			this.$refs.binpopup.open('center');
			this.currentIndex = index + 1;
			this.dgMessage = `${this.currentIndex}号仓`;
			for (let key of Object.keys(this.binDetail)) {
				this.binDetail[key] = "";
			}
			// 读取仓状态
			this.doRead(index);
		},
		unitPopup(index) {
			this.$refs.unitpopup.open('center');
			this.currentIndex = index + 1;
			this.command = 1;
			this.dgMessage = `检测单元${this.currentIndex}`;

			for (let key of Object.keys(this.unitInfo)) {
				this.unitInfo[key] = "";
			}
			// 读取仓状态
			this.doRead(index);
		},

		isSetting() {
			switch (this.type) {
				case "0": //主控参数
					// 判断是否为空,给出提示
					for (let i in this.masterInfo) {
						if (!this.masterInfo[i] && this.masterInfo[i] != '0') {
							this.$Toast.none(`${masterMessage2[i]}为空！`);
							return;
						}
					}
					break;
				case "1": //仓控参数
					for (let i in this.binDetail) {
						if (!this.binDetail[i] && this.binDetail[i] != '0') {
							this.$Toast.none(`${binMessage2[i]}为空！`);
							return;
						}
					}
					break;
				case "2": //检测单元参数
					for (let i in this.unitInfo) {
						if (!this.unitInfo[i] && this.unitInfo[i] != '0') {
							this.$Toast.none(`${unitMessage2[i]}为空！`);
							return;
						}
					}
					break;
			}

			let that = this;
			uni.showModal({
				title: '提示',
				content: '确定要设置参数吗？',
				success(res) {
					if (res.confirm) {
						that.doVerify();
					}
				}
			})
		},
		// 参数配置验证
		doVerify() {
			// 被发送的数据
			let sendData = [];
			switch (this.type) {
				case "0": //主控参数
					sendData = [this.masterInfo.param1, this.masterInfo.param2, this.masterInfo.param3, this.masterInfo
						.param4, this.masterInfo.param5
					];
					break;
				case "1": //仓控参数
					sendData = [...Set2Byte(this.binDetail.param1),this.binDetail.param2,this.binDetail.param3,this.binDetail.param4,
					...Set2Byte(this.binDetail.param5),this.binDetail.param6,this.binDetail.param7,this.binDetail.param8,
					...Set2Byte(this.binDetail.param9),...Set2Byte(this.binDetail.param10),...Set2Byte(this.binDetail.param11),this.binDetail.param12];
					break;
				case "2": //检测单元参数
				let param11=bitToStr([this.unitInfo.param11, this.unitInfo.param12, 0, 0,0,0,0,0]);
					sendData = [...Set2Byte(this.unitInfo.param1),this.unitInfo.param2,this.unitInfo.param3,...Set2Byte(this.unitInfo.param4),
					this.unitInfo.param5,this.unitInfo.param6,this.unitInfo.param7,this.unitInfo.param8,this.unitInfo.param9,this.unitInfo.param10,
					param11
					];
					break;
			}

			// 设置、控制： 被发送的数据需要进行加密
			let aesData = AESEncrypt(sendData.join('')); //加密数据
			console.log(sendData)
			console.log(sendData.join(''))
			console.log('对字符串进行AES加密处理结果--------')
			console.log(aesData)
			let decimalArray = aesData.match(/.{1,2}/g).map(hex => parseInt(hex, 16));
			console.log(decimalArray)
			console.log('数据区========')
			console.log(paraconfigdata(decimalArray))
			// dataUnit数据单元, operaType操作类型, addr地址, len数据区长度=rawbufflen+5, pack包号（单包取0，多包用上面的函数自动调用）, databuff数据区=snddatabuff整个数据区数组
			let datas = DataGet(this.command, 2, 0, decimalArray.length + 5, 0, paraconfigdata(decimalArray));

			this.doSetting(datas);
		},
		// 下发参数
		doSetting(datas) {
			let that = this;
			let buffer = arrayToBuffer(datas);
			// const uint8Array = new Uint8Array(buffer);
			// console.log(uint8Array)
			// const newArray = Array.from(uint8Array);
			console.log('这是发送的数据-------dosetting')
			console.log(ab2hex(buffer))
			let {
				deviceId,
			} = this.deviceInfo;
			uni.writeBLECharacteristicValue({
				deviceId,
				serviceId,
				characteristicId: characteristicId3,
				// 这里的value是ArrayBuffer类型
				value: buffer,
				success(res) {
					console.log('这是成功的结果--------')
					console.log(res)
					console.log(res.errMsg)
					// console.log(ab2hex(res.value))
					// const uint8Array = new Uint8Array(res.value);
					// console.log(uint8Array)
					// const newArray = Array.from(uint8Array);
					// console.log(newArray)
					// let value = hexCharCodeToStr(ab2hex(res.value));
					// console.log(value)
					// that.$Toast.none(value[resultMessage]);
					setTimeout(() => {
						
					
					uni.readBLECharacteristicValue({
						deviceId,
						serviceId,
						characteristicId: characteristicId3,
						success(res1) {
							console.log(res1)
							uni.onBLECharacteristicValueChange(function(res2) {
								console.log(res2)
							})
						},
						fail(fal) {
							console.log(fal)
						}
					})
					},500)
				},
				fail(err) {
					console.log('这是失败的结果======')
					console.log(err)
					that.$Toast.none(`${that.dgMessage}设置失败!`);
				}
			})
		},
	},
}